package org.example.exp3.utils;

import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import java.io.File;

public class XMLUtil {
    /**
     * 该方法用于从XML配置文件中提取图表类型,并返回类型名
     * @param path xml文件的路径
     * @param tagName 标签的名字
     * @return 获取的值
     */
    public static String getResultByName(String path, String tagName) {
        try {
            //创建文档对象
            DocumentBuilderFactory dFactory = DocumentBuilderFactory.newInstance();
            DocumentBuilder builder = dFactory.newDocumentBuilder();
            Document doc;
            doc = builder.parse(new File(path));

            //获取包含图表类型的文本结点
            NodeList nl = doc.getElementsByTagName(tagName);
            Node classNode = nl.item(0).getFirstChild();
            String result = classNode.getNodeValue().trim();
            return result;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    public static Object getBean(String path, String tagName){
        String className = getResultByName(path, tagName);
        try {
            Class clazz = Class.forName(className);
            Object obj = clazz.newInstance();
            return obj;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }
}
